const OFFSCREEN_DOCUMENT_PATH = chrome.runtime.getURL('offscreen/offscreen.html');

// 是否存在
async function hasOffscreenDocument() {
    if ('getContexts' in chrome.runtime) {
        const contexts = await chrome.runtime.getContexts({
            contextTypes: ['OFFSCREEN_DOCUMENT'],
            documentUrls: [OFFSCREEN_DOCUMENT_PATH],
        });
        return Boolean(contexts.length);
    } else {
        const matchedClients = await clients.matchAll();
        return await matchedClients.some((client) => {
            client.url.includes(chrome.runtime.id);
        });
    }
}

let creating; // A global promise to avoid concurrency issues
async function setupOffscreenDocument() {
    // Check all windows controlled by the service worker to see if one
    // of them is the offscreen document with the given path

    const existingContexts = await hasOffscreenDocument();

    if (existingContexts) {
        return;
    }

    // create offscreen document
    if (creating) {
        await creating;
    } else {
        creating = chrome.offscreen.createDocument({
            url: OFFSCREEN_DOCUMENT_PATH,
            reasons: ['CLIPBOARD'],
            justification: 'reason for needing the document',
        });
        await creating;
        creating = null;
    }
}

setupOffscreenDocument();
